package com.nexgo.payment.action.inputamount;

import android.support.annotation.NonNull;

import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.widget.keyboard.NumKeyBoard;
import com.nexgo.sound.BeeperManager;
import com.nexgo.sound.SoundManager;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by xiaox on 2017/7/5.
 */

public class InputAmountPresenter implements InputAmountContract.Presenter {
    private InputAmountContract.View mView;
    private DataSource mRepository;
    private TransData mTransData;
    private boolean mIsFistTime = true;
    private final SoundManager mSoundManager;
    private final BeeperManager mBeeperManager;

    public InputAmountPresenter(@NonNull InputAmountContract.View view, @NonNull DataSource repository, @NonNull TransData transData) {
        mView = checkNotNull(view);
        mRepository = checkNotNull(repository);
        mTransData = checkNotNull(transData);
        view.setPresenter(this);
        mSoundManager = new SoundManager();
        mBeeperManager = new BeeperManager();
    }


    @Override
    public void start() {
        if (mIsFistTime) {
            mSoundManager.play(SoundManager.Type.ENTER_AMOUNT);
            mIsFistTime = false;
        }
    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {
        mSoundManager.stop();
    }

    @Override
    public void pressKey(NumKeyBoard.KEY_TYPE keyType) {
        mBeeperManager.beep(BeeperManager.Type.NORMAL);
    }

    @Override
    public void importAmount(String amount) {
        if (TransType.REFUND.equals(mTransData.getTransType()) ||
                TransType.SCAN_REFUND.equals(mTransData.getTransType())) {
            if (checkRefundAmount(amount)) {
                mView.showOverRefundAmount();
            } else {
                mView.showConfirmAmount(amount);
            }
        } else {
            mView.showSuccessful(amount);
        }
    }

    @Override
    public void confirmAmount(String amount) {
        mView.showSuccessful(amount);
    }

    /**
     * 检测金额是否超过最大退货金额
     *
     * @param amount
     * @return
     */
    private boolean checkRefundAmount(String amount) {
        try {
            String maxRefundAmount = mRepository.getParamValue(PreferencesConstants.MAX_REFUND_AMOUNT);
            long inputAmount = Long.valueOf(amount);
            long maxLimitAmount = Long.valueOf(maxRefundAmount);
            return inputAmount > maxLimitAmount;
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
    }
}
